//
//  TTToTweetViewController.swift
//  WeiBo
//
//  Created by 涂永江 on 2017/6/12.
//  Copyright © 2017年 涂永江. All rights reserved.
//

import UIKit
import SVProgressHUD

class TTToTweetViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }
   // MARK:  -- 设置titleView
    fileprivate lazy var titleLabel:UILabel = {
      let label = UILabel()
       if let name = TTHMUserAccountViewModel.sharedAccountModel.accountModel?.name
       {
        let content = "发微博\n\(name)"
        let atrrute = NSMutableAttributedString(string: content)
        let rage = (content as NSString).range(of: "\(name)")
        atrrute.addAttributes([NSFontAttributeName:UIFont.systemFont(ofSize: 13),NSForegroundColorAttributeName:UIColor.orange], range: rage)
         label.attributedText = atrrute
        }else
       {
        
        label.text = "发微博"
        }
          label.textAlignment = .center
          label.numberOfLines = 0
          label.sizeToFit()
        
        return label
    }()
    // MARK:  --设置右边按钮
    fileprivate lazy var rightButton:UIButton = {
       let button = UIButton()
    button.addTarget(self, action: #selector(btnAction), for: .touchUpInside)
    button.setTitle("发送", for: .normal)
    button.setBackgroundImage(UIImage(named: "common_button_orange"), for: .normal)
    button.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), for: .highlighted)
    button.setBackgroundImage(UIImage(named: "common_button_white_disable"), for: .disabled)
    button.setTitleColor(UIColor.black, for: .normal)
    button.setTitleColor(UIColor.darkGray, for: .disabled)
    button.titleLabel?.font = UIFont.systemFont(ofSize: 14)
   
    button.width = 45
    button.height = 35
        
        return button
    }()
    // MARK:  --设置textView
    fileprivate lazy var textView:TTToTextView = {
        let textv = TTToTextView()
        textv.delegate = self
        textv.poshoder = "曾志是个大傻逼嘻嘻嘻嘻嘻嘻嘻我嘻嘻嘻嘻嘻嘻嘻 嘻嘻嘻ixixixixixixixixixii"
        textv.alwaysBounceVertical = true
        return textv
    }()

    // MARK:  --设置图片的colltionView
    fileprivate lazy var pictureView:TTToCollectionView = {
        let pictureView = TTToCollectionView()
        pictureView.isHidden = true
        return pictureView
    }()
    
    // MARK:  --设置toolBar
    private lazy var toolBar:TTToStackView = {
        let toolBar = TTToStackView()
        return toolBar
        
    }()
    //添加发送的点击事件
    @objc private func btnAction()
    {
        // 1. 拿到token
        let token = TTHMUserAccountViewModel.sharedAccountModel.accountModel?.access_token
        
        if pictureView.imageArray.count>0{
            
            TTToolsManager.sharedManager.sendPicture(token: token!, textContent: textView.text, pic: pictureView.imageArray.first!, sucess: { (resbonse, error) in
                if error != nil{
                    SVProgressHUD.showError(withStatus: "发送失败")
                    return
                }
                SVProgressHUD.showSuccess(withStatus: "发送成功")
                self.view.endEditing(true)
                let window = UIApplication.shared.keyWindow
                
                let tab = TTTabarViewController()
                window?.rootViewController = tab
            })
            
        }else{
            
            TTToolsManager.sharedManager.sendText(token: token!, textContent: textView.text) { (rebonse, error) in
                if error != nil{
                    SVProgressHUD.showError(withStatus: "发送失败")
                    return
                }
                SVProgressHUD.showSuccess(withStatus: "发送成功")
                self.view.endEditing(true)
                let window = UIApplication.shared.keyWindow
                
                let tab = TTTabarViewController()
                window?.rootViewController = tab
            }
        }
    }
    
  private func setupUI()
  {
    //注册键盘通知
    NotificationCenter.default.addObserver(self, selector: #selector(keyBrodyChange(noto:)), name: NSNotification.Name.UIKeyboardDidChangeFrame, object: nil)
    self.navigationItem.leftBarButtonItem = UIBarButtonItem(title1: "取消", target: self, action: #selector(caller))
    self.navigationItem.titleView = titleLabel
    self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightButton)
    self.navigationItem.rightBarButtonItem?.isEnabled = false
    setUI()
  }
    
    func keyBrodyChange(noto:Notification)
    {
 
        let rect = noto.userInfo?[UIKeyboardFrameEndUserInfoKey] as! CGRect
        toolBar.snp.updateConstraints { (make) in
            make.bottom.equalTo(view).offset(rect.origin.y - screnssHeight)
        }
        UIView.animate(withDuration: 0.2) {
            self.view.layoutIfNeeded()
        }
    
    }
    
    private func setUI()
    {
     view.addSubview(textView)
     textView.addSubview(pictureView)
     view.addSubview(toolBar)
      textView.snp.makeConstraints { (make) in
    make.top.leading.trailing.equalTo(view)
    make.bottom.equalTo(toolBar.snp.bottom)
        }
        pictureView.snp.makeConstraints { (make) in
            make.top.equalTo(textView).offset(100)
            make.centerX.equalTo(textView)
            make.width.equalTo(textView).offset(-20)
            make.height.equalTo(textView.snp.width).offset(-20)
        }
    toolBar.snp.makeConstraints { (make) in
        make.leading.trailing.bottom.equalTo(view)
        make.height.equalTo(35)
        
        }
        toolBar.btnColse = {[unowned self] (type)->() in
        
            switch type {
            case .picture:
               self.bounseCamerie()
            case .mention:
                print("@")
            case .trend:
                print("#")
            case .emoticon:
                print("表情")
            case .add:
                print("+")
            }
        
        }
        
        pictureView.addPicColse = {[unowned self] in
        
        self.bounseCamerie()
        }
    }

    private func bounseCamerie()
    {
       let imagePick = UIImagePickerController()
        imagePick.delegate = self
        
        if UIImagePickerController.isSourceTypeAvailable(.camera)
        {
        imagePick.sourceType = .camera
        
        }else
        {
        imagePick.sourceType = .photoLibrary
        }
    
        self.present(imagePick, animated: true, completion: nil)
    }
    
   // MARK:  --取消按钮点击事件
    @objc private func caller(){
    dismiss(animated: true, completion: nil)
    
    }
}

// MARK:  --UITextView代理
extension TTToTweetViewController:UITextViewDelegate
{
    func textViewDidChange(_ textView: UITextView) {
        self.navigationItem.rightBarButtonItem?.isEnabled = textView.hasText
    }
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        self.view.endEditing(true)
    }
}

extension TTToTweetViewController:UIImagePickerControllerDelegate,UINavigationControllerDelegate
{
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        let image = info[UIImagePickerControllerOriginalImage] as! UIImage
       let currentImage = scalePicture(image: image, scaleWidth: 200)
        pictureView.show(image: currentImage)
        picker.dismiss(animated: true, completion: nil)
       }
    
    //压缩图片
    func scalePicture(image:UIImage,scaleWidth:CGFloat) ->UIImage
    {
      //压缩后图片的高度
     let scaleHeight = scaleWidth/image.size.width * image.size.height
        
     let picSize = CGSize(width: scaleWidth, height: scaleHeight)
        
        UIGraphicsBeginImageContext(picSize)
        let rect = CGRect(origin: CGPoint.zero, size: picSize)
        image.draw(in: rect)
        
        let currentImage = UIGraphicsGetImageFromCurrentImageContext()
        
       return currentImage!
    }
  


}
